package dao;

import model.Message;
import model.User;
import util.JDBCConnection;
import util.JDBCFactory;
import util.ResultList;

import java.math.BigInteger;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

public class MessagesManager implements MessagesManagement {

    private static List<Message> getResultList(List<Object[]> list)
    {
        Message msg = null;

        List<Message> result = new ResultList<>();

        for(Object[] row : list)
        {
            msg = new Message();

            msg.setMsg_id((Long) row[0]);
            msg.setMsgtyp_id((Long) row[1]);
            msg.setMsg_sender((Long) row[2]);
            msg.setMsg_content((String) row[3]);
            msg.setMsg_ctime((LocalDateTime) row[4]);

            result.add(msg);
        }
        return result;
    }

    private int deleteMessageRecordBySender(long senderID)
    {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            int count = conn.update(
                    "delete from t_msgsends s where exists " +
                            "(select m.msg_id from t_messages m where m.msg_id = s.msg_id and m.msg_sender = ?)",
                    senderID
            );
            JDBCFactory.returnBack(conn);
            return count;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return 0;
        }
    }

    @Override
    public List<Message> findAll(int pageSize, int page) {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            List<Object[]> list = conn.query("select * from t_messages limit ?, ?", (page - 1) * pageSize, pageSize);
            JDBCFactory.returnBack(conn);

            return getResultList(list);
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public List<Message> findByTime(LocalDateTime begintime,LocalDateTime endtime) {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            List<Object[]> list = conn.query("select * from t_messages t where t.msg_ctime between ? and ?", begintime, endtime);
            JDBCFactory.returnBack(conn);

            return getResultList(list);
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public List<Message> findBySender(long senderId) {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            List<Object[]> list = conn.query("select * from t_messages t where t.msg_sender = ?", senderId);
            JDBCFactory.returnBack(conn);

            return getResultList(list);
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public int deleteMessagesBySender(long senderID)
    {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            //开启事务
            conn.start();

            //获得该发送者发送的所有消息的id
            List<Object[]> msgIds = conn.query("select msg_id from t_messages where msg_sender = ?", senderID);

            conn.preparedUpdateBatch("delete from t_msgsends where msg_id = ?");
            for (Object[] row : msgIds) conn.addUpdateBatch(row[0]);
            conn.preparedUpdateBatch("delete from t_messages where msg_id = ?");
            for (Object[] row : msgIds) conn.addUpdateBatch(row[0]);
            conn.submitUpdateBatch();

            //提交事务
            conn.commit();
            JDBCFactory.returnBack(conn);
            return msgIds.size();
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return 0;
        }
    }

    @Override
    public int deleteMessagesByReciver(long reciverID)
    {
        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            int count = conn.update("delete from t_msgsends where u_id = ?", reciverID);
            JDBCFactory.returnBack(conn);

            return count;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return 0;
        }
    }

    private int addMessageRecord(JDBCConnection conn, Message msg, List<User> recivers)
    {
        long msgId = msg.getMsg_id();
        try {
            conn.preparedUpdateBatch("insert into t_msgsends values(?, ?, '未读', CURRENT_TIMESTAMP)");
            for (User reciver : recivers) conn.addUpdateBatch(msgId, reciver.getU_id());
            conn.submitUpdateBatch();

            return recivers.size();
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return 0;
        }
    }

    @Override
    public int sendMessage(long msgTypeId, long msgSenderID, String msgContent, List<User> recivers)
    {
        if(msgContent == null || recivers == null) return 0;
        Message msg = new Message();
        msg.setMsgtyp_id(msgTypeId);
        msg.setMsg_sender(msgSenderID);
        msg.setMsg_content(msgContent);

        try {
            JDBCConnection conn = JDBCFactory.takeJDBC();
            //开启事务
            conn.start();

            //添加消息，获得消息的ID
            msg.setMsg_id(((BigInteger) conn.updateForGeneratedKey(
                    "insert into t_messages values(null, ?, ?, ?, CURRENT_TIMESTAMP)",
                    msgTypeId, msgSenderID, msgContent)
            ).longValue());
            int count = addMessageRecord(conn, msg, recivers);

            //提交事务
            conn.commit();
            JDBCFactory.returnBack(conn);
            return count;
        } catch(SQLException e) {
            System.err.println(e.getMessage());
            return 0;
        }
    }

    public static void main(String[] args) {
        //ResultListInterface<User> users = new LinkedList<>();

        //for(int i=1; i<=7; ++i) users.add(new User(i));

        //new MessagesManager().sendMessage(1L, 1L, "debugdebug", users);

        new MessagesManager().deleteMessagesBySender(1L);
    }
}
